import configService from '@/common/service/config.service.js'
const URL = 'ws://www.wan888.club:2000'
let timer = null
let socketTask = {
	socketOpen: false,
	sendMsg: null
}
socketTask = uni.connectSocket({
	url: URL,
	header: {
		'content-type': 'multipart/form-data',
		// 'content-type': 'application/json'
	},
	method: 'POST',
	success: (res) => {
	}
});


uni.onSocketOpen((res) => {
	socketTask.socketOpen = true;
	if(timer != null) {
		clearInterval(timer)
	}
});

uni.onSocketClose(function (res) {
	socketTask.socketOpen = false
	console.log('关闭连接');
	setInterval(() => {
		console.log("重新尝试连接")
		uni.connectSocket({
			url: URL,
			header: {
				'content-type': 'multipart/form-data',
				// 'content-type': 'application/json'
			},
			method: 'POST',
			success: (res) => {
			}
		});
	}, 1000)
});

uni.onSocketError((res) => {
	socketTask.socketOpen = false
	console.error('WebSocket连接打开失败，请检查！');
});

/**
 * 发送消息
 * */
socketTask.sendMsg = (msg) => {
	if (socketTask.socketOpen) {
		uni.sendSocketMessage({
			data: JSON.stringify(msg)
		});
	} 
}


export {
	socketTask
}